{% extends 'stocks/base.html' %}
{% load static %}

{% block title %}{{ title }}{% endblock %}

{% block extra_head %}
<!-- 使用本地静态文件避免CDN网络问题 -->
<script src="{% static 'js/chart.js' %}"></script>
<script src="{% static 'js/chartjs-chart-financial.js' %}"></script>
<style>
    .chart-container {
        position: relative;
        height: 400px;
        margin-bottom: 20px;
    }
    .financial-card {
        height: 300px;
    }
    .tab-content {
        padding: 20px 0;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row mb-4">
        <div class="col-12">
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="{% url 'stock_list' %}">股票列表</a></li>
                    <li class="breadcrumb-item"><a href="{% url 'stock_detail' stock.symbol %}">{{ stock.symbol }} - {{ stock.name }}</a></li>
                    <li class="breadcrumb-item active">数据可视化</li>
                </ol>
            </nav>
            <h2>
                <i class="bi bi-graph-up"></i> {{ stock.symbol }} - {{ stock.name }} 数据可视化
            </h2>
        </div>
    </div>

    <!-- 选项卡导航 -->
    <ul class="nav nav-tabs" id="visualizationTabs" role="tablist">
        <li class="nav-item" role="presentation">
            <button class="nav-link active" id="kline-tab" data-bs-toggle="tab" data-bs-target="#kline" type="button" role="tab" aria-controls="kline" aria-selected="true">
                <i class="bi bi-bar-chart"></i> K线图
            </button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" id="financial-tab" data-bs-toggle="tab" data-bs-target="#financial" type="button" role="tab" aria-controls="financial" aria-selected="false">
                <i class="bi bi-calculator"></i> 财务指标
            </button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" id="volume-tab" data-bs-toggle="tab" data-bs-target="#volume" type="button" role="tab" aria-controls="volume" aria-selected="false">
                <i class="bi bi-speedometer2"></i> 成交量分析
            </button>
        </li>
    </ul>

    <div class="tab-content" id="visualizationTabContent">
        <!-- K线图选项卡 -->
        <div class="tab-pane fade show active" id="kline" role="tabpanel" aria-labelledby="kline-tab">
            <div class="card">
                <div class="card-header">
                    <h5 class="card-title mb-0">K线图 - {{ stock.symbol }} 最近60个交易日</h5>
                </div>
                <div class="card-body">
                    <div class="chart-container">
                        <canvas id="candleChart"></canvas>
                    </div>
                </div>
            </div>
        </div>

        <!-- 财务指标选项卡 -->
        <div class="tab-pane fade" id="financial" role="tabpanel" aria-labelledby="financial-tab">
            <div class="row">
                <div class="col-md-6">
                    <div class="card financial-card">
                        <div class="card-header">
                            <h6 class="card-title mb-0">ROE趋势</h6>
                        </div>
                        <div class="card-body">
                            <canvas id="roeChart"></canvas>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="card financial-card">
                        <div class="card-header">
                            <h6 class="card-title mb-0">利润率分析</h6>
                        </div>
                        <div class="card-body">
                            <canvas id="profitChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="row mt-4">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header">
                            <h6 class="card-title mb-0">财务指标详情</h6>
                        </div>
                        <div class="card-body">
                            {% if financial_data %}
                                <div class="table-responsive">
                                    <table class="table table-striped">
                                        <thead>
                                            <tr>
                                                <th>报告期</th>
                                                <th>ROE(%)</th>
                                                <th>销售净利率(%)</th>
                                                <th>毛利率(%)</th>
                                                <th>资产负债率(%)</th>
                                                <th>流动比率</th>
                                                <th>收入增长率(%)</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            {% for data in financial_data %}
                                            <tr>
                                                <td>{{ data.date }}</td>
                                                <td>{{ data.roe|default:"-" }}</td>
                                                <td>{{ data.net_profit_margin_on_sales|default:"-" }}</td>
                                                <td>{{ data.gross_profit_margin|default:"-" }}</td>
                                                <td>{{ data.asset_liability_ratio|default:"-" }}</td>
                                                <td>{{ data.current_ratio|default:"-" }}</td>
                                                <td>{{ data.main_business_income_growth_rate|default:"-" }}</td>
                                            </tr>
                                            {% endfor %}
                                        </tbody>
                                    </table>
                                </div>
                            {% else %}
                                <div class="alert alert-info">
                                    <i class="bi bi-info-circle"></i> 暂无财务数据
                                </div>
                            {% endif %}
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 成交量分析选项卡 -->
        <div class="tab-pane fade" id="volume" role="tabpanel" aria-labelledby="volume-tab">
            <div class="card">
                <div class="card-header">
                    <h5 class="card-title mb-0">成交量分析</h5>
                </div>
                <div class="card-body">
                    <div class="chart-container">
                        <canvas id="volumeChart"></canvas>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 操作按钮 -->
    <div class="row mt-4">
        <div class="col-12">
            <div class="d-flex gap-2">
                <a href="{% url 'stock_list' %}" class="btn btn-secondary">
                    <i class="bi bi-arrow-left"></i> 返回股票列表
                </a>
                <a href="{% url 'stock_detail' stock.symbol %}" class="btn btn-outline-primary">
                    <i class="bi bi-info-circle"></i> 查看详情
                </a>
                <a href="{% url 'daily_data' stock.symbol %}" class="btn btn-outline-success">
                    <i class="bi bi-bar-chart"></i> 交易数据
                </a>
                <a href="{% url 'financial_data' stock.symbol %}" class="btn btn-outline-info">
                    <i class="bi bi-calculator"></i> 财务数据
                </a>
            </div>
        </div>
    </div>
</div>

<script>
// 调试信息 - 显示数据统计
console.log('=== 股票可视化调试信息 ===');
console.log('股票代码:', '{{ stock.symbol }}');
console.log('股票名称:', '{{ stock.name }}');

// 准备K线图数据 - 使用JSON安全解析
let ohlcData = [];
try {
    ohlcData = JSON.parse('{{ ohlc_data_json|escapejs }}');
    console.log('OHLC数据解析成功，记录数:', ohlcData.length);
    if (ohlcData.length > 0) {
        console.log('第一条OHLC数据:', ohlcData[0]);
        console.log('最后一条OHLC数据:', ohlcData[ohlcData.length - 1]);
    }
} catch (e) {
    console.error('Error parsing OHLC data:', e);
    ohlcData = [];
}

// 准备财务数据
let financialData = [];
try {
    financialData = JSON.parse('{{ financial_data_json|escapejs }}');
    console.log('财务数据解析成功，记录数:', financialData.length);
    if (financialData.length > 0) {
        console.log('财务数据样例:', financialData[0]);
    }
} catch (e) {
    console.error('Error parsing financial data:', e);
    financialData = [];
}

// 初始化K线图
function initCandleChart() {
    try {
        const ctx = document.getElementById('candleChart');
        if (!ctx) {
            console.error('Canvas element not found');
            return;
        }
        
        // 检查数据是否有效
        if (!ohlcData || !Array.isArray(ohlcData) || ohlcData.length === 0) {
            console.error('Invalid OHLC data:', ohlcData);
            ctx.getContext('2d').fillStyle = '#6c757d';
            ctx.getContext('2d').font = '16px Arial';
            ctx.getContext('2d').textAlign = 'center';
            ctx.getContext('2d').fillText('暂无K线数据', ctx.width / 2, ctx.height / 2);
            return;
        }
        
        const chart = new Chart(ctx, {
            type: 'candlestick',
            data: {
                datasets: [{
                    label: '{{ stock.symbol }} 股价',
                    data: ohlcData,
                    color: {
                        up: 'rgba(255, 0, 0, 1)',
                        down: 'rgba(0, 255, 0, 1)',
                        unchanged: 'rgba(0, 0, 255, 1)'
                    }
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    title: {
                        display: true,
                        text: '{{ stock.symbol }} K线图'
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                const point = context.raw;
                                return [
                                    '开盘: ' + point.o,
                                    '最高: ' + point.h,
                                    '最低: ' + point.l,
                                    '收盘: ' + point.c,
                                    '成交量: ' + point.v.toLocaleString()
                                ];
                            }
                        }
                    }
                },
                scales: {
                    x: {
                        type: 'time',
                        time: {
                            unit: 'day',
                            displayFormats: {
                                day: 'MM-dd'
                            }
                        }
                    },
                    y: {
                        beginAtZero: false
                    }
                }
            }
        });
    } catch (error) {
        console.error('Error initializing candle chart:', error);
    }
}

// 初始化财务图表
function initFinancialCharts() {
    try {
        let financialData = [];
        try {
            financialData = JSON.parse('{{ financial_data_json|escapejs }}');
        } catch (e) {
            console.error('Error parsing financial data:', e);
            financialData = [];
        }
        console.log('Financial Data:', financialData);
        
        if (!financialData || !Array.isArray(financialData) || financialData.length === 0) {
            console.log('No financial data available');
            return;
        }
        
        // ROE趋势图
        const roeCtx = document.getElementById('roeChart');
        if (roeCtx) {
            new Chart(roeCtx, {
                type: 'line',
                data: {
                    labels: financialData.map(d => d.date),
                    datasets: [{
                        label: 'ROE(%)',
                        data: financialData.map(d => d.roe),
                        borderColor: 'rgb(75, 192, 192)',
                        tension: 0.1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false
                }
            });
        }

        // 利润率对比图 - 只显示有数据的指标
        const profitCtx = document.getElementById('profitChart');
        if (profitCtx) {
            // 过滤出有数据的指标
            const profitDatasets = [];
            
            // 检查销售净利率是否有数据
            const netProfitData = financialData.map(d => d.net_profit_margin_on_sales);
            if (netProfitData.some(val => val !== null)) {
                profitDatasets.push({
                    label: '销售净利率(%)',
                    data: netProfitData,
                    backgroundColor: 'rgba(255, 99, 132, 0.6)'
                });
            }
            
            // 检查毛利率是否有数据
            const grossProfitData = financialData.map(d => d.gross_profit_margin);
            if (grossProfitData.some(val => val !== null)) {
                profitDatasets.push({
                    label: '毛利率(%)',
                    data: grossProfitData,
                    backgroundColor: 'rgba(54, 162, 235, 0.6)'
                });
            }
            
            // 如果有任何利润率数据，才创建图表
            if (profitDatasets.length > 0) {
                new Chart(profitCtx, {
                    type: 'bar',
                    data: {
                        labels: financialData.map(d => d.date),
                        datasets: profitDatasets
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false
                    }
                });
            } else {
                // 如果没有利润率数据，显示提示信息
                const ctx = profitCtx.getContext('2d');
                ctx.fillStyle = '#6c757d';
                ctx.font = '16px Arial';
                ctx.textAlign = 'center';
                ctx.fillText('暂无利润率数据', profitCtx.width / 2, profitCtx.height / 2);
            }
        }
    } catch (error) {
        console.error('Error initializing financial charts:', error);
    }
}

// 初始化成交量图表
function initVolumeChart() {
    try {
        const ctx = document.getElementById('volumeChart');
        if (!ctx) {
            console.error('Volume chart canvas element not found');
            return;
        }
        
        // 检查数据是否有效
        if (!ohlcData || !Array.isArray(ohlcData) || ohlcData.length === 0) {
            console.error('Invalid OHLC data for volume chart:', ohlcData);
            ctx.getContext('2d').fillStyle = '#6c757d';
            ctx.getContext('2d').font = '16px Arial';
            ctx.getContext('2d').textAlign = 'center';
            ctx.getContext('2d').fillText('暂无成交量数据', ctx.width / 2, ctx.height / 2);
            return;
        }
        
        const volumeData = ohlcData.map(d => ({
            x: d.x,
            y: d.v
        }));

        new Chart(ctx, {
            type: 'bar',
            data: {
                datasets: [{
                    label: '成交量',
                    data: volumeData,
                    backgroundColor: 'rgba(153, 102, 255, 0.6)'
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    x: {
                        type: 'time',
                        time: {
                            unit: 'day'
                        }
                    },
                    y: {
                        beginAtZero: true
                    }
                }
            }
        });
    } catch (error) {
        console.error('Error initializing volume chart:', error);
    }
}

// 检查Chart.js Financial是否正确加载
function checkChartJSFinancial() {
    console.log('Checking if Chart.js is loaded...');
    console.log('typeof Chart:', typeof Chart);
    
    if (typeof Chart === 'undefined') {
        console.error('Chart.js is not loaded - checking script loading status');
        
        // 检查脚本是否加载失败
        const scripts = document.querySelectorAll('script');
        let chartJsLoaded = false;
        let financialLoaded = false;
        
        scripts.forEach(script => {
            if (script.src.includes('chart.js')) {
                console.log('Chart.js script found:', script.src);
                chartJsLoaded = true;
            }
            if (script.src.includes('chartjs-chart-financial')) {
                console.log('Chart.js Financial script found:', script.src);
                financialLoaded = true;
            }
        });
        
        if (!chartJsLoaded) {
            console.error('Chart.js script was not found in the DOM');
        }
        if (!financialLoaded) {
            console.error('Chart.js Financial script was not found in the DOM');
        }
        
        return false;
    }
    
    console.log('Chart.js version:', Chart.version);
    console.log('Available chart types:', Object.keys(Chart.controllers || {}));
    
    // 检查candlestick图表类型是否可用
    if (!Chart.controllers.candlestick) {
        console.error('Chart.js Financial (candlestick) is not loaded properly');
        return false;
    }
    
    console.log('Chart.js Financial loaded successfully');
    return true;
}

// 备用加载函数
function loadFallbackChartJS() {
    console.log('CDN加载失败，尝试备用CDN...');
    const script = document.createElement('script');
    script.src = 'https://unpkg.com/chart.js@4.5.0/dist/chart.min.js';
    script.onload = function() {
        console.log('备用Chart.js加载成功');
        loadFallbackFinancial();
    };
    script.onerror = function() {
        console.error('所有CDN源都失败，使用本地文件');
        useLocalChartJS();
    };
    document.head.appendChild(script);
}

function loadFallbackFinancial() {
    const script = document.createElement('script');
    script.src = 'https://unpkg.com/chartjs-chart-financial@1.2.0/dist/chartjs-chart-financial.min.js';
    script.onload = function() {
        console.log('备用Chart.js Financial加载成功');
        initAllCharts();
    };
    script.onerror = function() {
        console.error('所有Financial CDN源都失败');
        useLocalFinancial();
    };
    document.head.appendChild(script);
}

function useLocalChartJS() {
    console.log('尝试使用本地Chart.js文件');
    // 这里可以添加本地文件加载逻辑
    const errorDiv = document.createElement('div');
    errorDiv.style.cssText = 'background: #fff3cd; color: #856404; padding: 15px; margin: 10px; border-radius: 5px;';
    errorDiv.innerHTML = '<strong>网络连接问题:</strong> 无法从CDN加载图表库。<br>请检查网络连接或联系管理员配置本地静态文件。';
    document.querySelector('.container-fluid').prepend(errorDiv);
}

function useLocalFinancial() {
    console.log('尝试使用本地Chart.js Financial文件');
    // 这里可以添加本地文件加载逻辑
}

function initAllCharts() {
    if (typeof Chart !== 'undefined' && Chart.controllers && Chart.controllers.candlestick) {
        console.log('Chart.js Financial已加载，开始初始化图表');
        initCandleChart();
        initFinancialCharts();
        initVolumeChart();
    } else {
        console.error('Chart.js Financial仍然未正确加载');
    }
}

// 页面加载完成后初始化图表
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM loaded, checking Chart.js Financial...');
    
    // 立即检查一次
    if (checkChartJSFinancial()) {
        initAllCharts();
    } else {
        // 如果未加载，等待2秒再检查（给本地文件时间加载）
        setTimeout(function() {
            if (!checkChartJSFinancial()) {
                // 如果Chart.js Financial没有正确加载，显示错误信息
                const errorDiv = document.createElement('div');
                errorDiv.style.cssText = 'background: #f8d7da; color: #721c24; padding: 15px; margin: 10px; border-radius: 5px;';
                errorDiv.innerHTML = '<strong>图表库加载错误:</strong> 本地Chart.js文件加载失败。<br>请检查静态文件是否正确配置，或联系管理员。';
                document.querySelector('.container-fluid').prepend(errorDiv);
            } else {
                initAllCharts();
            }
        }, 2000); // 给脚本2秒钟时间加载
    }
});
</script>
{% endblock %}
